package com.rabbitmq.provider.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数;消息到达broker则触发回调
        rabbitTemplate.setMandatory(true);

        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("ConfirmCallback:     " + "相关数据：" + correlationData);
            System.out.println("ConfirmCallback:     " + "确认情况：" + ack);
            System.out.println("ConfirmCallback:     " + "原因：" + cause);
        });

        //找到交换机，没找到队列才会触发该回调
        rabbitTemplate.setReturnsCallback(returnMessage -> {
            System.out.println("ReturnCallback:     " + "消息：" + returnMessage.getMessage());
            System.out.println("ReturnCallback:     " + "回应码：" + returnMessage.getReplyCode());
            System.out.println("ReturnCallback:     " + "回应信息：" + returnMessage.getReplyText());
            System.out.println("ReturnCallback:     " + "交换机：" + returnMessage.getExchange());
            System.out.println("ReturnCallback:     " + "路由键：" + returnMessage.getRoutingKey());
        });
        return rabbitTemplate;
    }
}
